package com.huluobo.a2109amvvmdemo.lifecycle;

import android.os.CountDownTimer;
import android.util.Log;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.huluobo.a2109amvvmdemo.viewmodel.ADViewModel;

/**
 * Created by LC on 2023/11/27.
 */
public class ADManager implements LifecycleObserver {
    public static final String TAG = "ADManager";

    private CountDownTimer countDownTimer;

    public ADManager(ADViewModel adViewModel) {
        countDownTimer = new CountDownTimer(adViewModel.millisInFuture, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.i(TAG, "广告剩余:" + (int) millisUntilFinished / 1000);
                adViewModel.setTimingResult(millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                Log.i(TAG, "广告结束");
            }
        };
    }

    //实现了LifecycleObserver 现在可以通过观察被观察者的生命周期来调用对应的方法
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void start() {
        Log.i(TAG, "开始计时");
        countDownTimer.start();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void stop() {
        Log.i(TAG, "结束计时");
        countDownTimer.cancel();
    }
}
